package org.jd.export.repo;

import lombok.RequiredArgsConstructor;
import org.jd.export.model.ColumnInfo;
import org.jd.export.model.TableInfo;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class SchemaRepository {

    private final JdbcTemplate jdbcTemplate;

    /**
     * 获取指定数据库中所有表的基本信息
     */
    public List<TableInfo> getAllTables(String databaseName) {
        // 查询所有表名和表描述
        String tableSql = """
            SELECT TABLE_NAME, TABLE_COMMENT 
            FROM information_schema.TABLES 
            WHERE TABLE_SCHEMA = ? 
            ORDER BY TABLE_NAME
        """;
        
        return jdbcTemplate.query(tableSql, new TableRowMapper(), databaseName)
                .stream()
                .peek(table -> {
                    // 为每个表查询列信息
                    List<ColumnInfo> columns = getTableColumns(databaseName, table.getTableName());
                    table.setColumnInfos(columns);
                })
                .toList();
    }

    /**
     * 获取指定表的所有列信息
     */
    private List<ColumnInfo> getTableColumns(String databaseName, String tableName) {
        String columnSql = """
            SELECT 
                COLUMN_NAME, 
                COLUMN_TYPE, 
                IS_NULLABLE, 
                COLUMN_COMMENT,
                ORDINAL_POSITION
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? 
            ORDER BY ORDINAL_POSITION
        """;
        
        return jdbcTemplate.query(columnSql, new ColumnRowMapper(), databaseName, tableName);
    }

    /**
     * 表信息行映射器
     */
    private static class TableRowMapper implements RowMapper<TableInfo> {
        @Override
        public TableInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
            TableInfo table = new TableInfo();
            table.setTableName(rs.getString("TABLE_NAME"));
            table.setTableComment(rs.getString("TABLE_COMMENT"));
            return table;
        }
    }

    /**
     * 列信息行映射器
     */
    private static class ColumnRowMapper implements RowMapper<ColumnInfo> {
        @Override
        public ColumnInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
            ColumnInfo column = new ColumnInfo();
            column.setColumnName(rs.getString("COLUMN_NAME"));
            column.setColumnType(rs.getString("COLUMN_TYPE"));
            column.setIsNullable(rs.getString("IS_NULLABLE"));
            column.setColumnComment(rs.getString("COLUMN_COMMENT"));
            column.setOrdinalPosition(rs.getInt("ORDINAL_POSITION"));
            return column;
        }
    }
}
